package com.jd.system.service.impl;


import com.jd.system.domain.Menu;
import com.jd.system.mapper.MenuMapper;
import com.jd.system.service.IMenuService;
import com.jd.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> menuTree() {
        List<Menu> all = menuMapper.loadAll();
        Map<Long, Menu> map = new HashMap<>();
        for (Menu menu : all) {
            map.put(menu.getId(),menu);
        }
        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu : all) {
            if (menu.getParentId()==null){
                menuTree.add(menu);
            } else {
                Long parentId = menu.getParentId();
                //根据父部门id获取父部门
                Menu parentMenu = map.get(parentId);
                //parentMenu.getChildren().add(menu);
                //将自己添加到父部门的集合列表中
                List<Menu> children = parentMenu.getChildren();
                children.add(menu);
            }
        }
        return menuTree;
    }
}
